<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="工号" prop="username">
            <el-input v-model="form.username" placeholder="请输入工号" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <splitpanes>
      <pane size="25">
        <div class="layout-padding-auto layout-padding-view">
          <el-scrollbar>
            <query-tree :placeholder="$t('common.queryDeptTip')" :query="deptData.queryList" :show-expand="true"
              @node-click="handleNodeClick">
              <template #default="{ node, data }">
                <el-tooltip v-if="data.isLock" class="item" effect="dark" :content="$t('sysuser.noDataScopeTip')"
                  placement="right-start">
                  <span>{{ node.label }}
                    <SvgIcon name="ele-Lock" />
                  </span>
                </el-tooltip>
                <span v-if="!data.isLock">{{ node.label }}</span>
              </template>
            </query-tree>
          </el-scrollbar>
        </div>
      </pane>
      <pane class="ml8">
        <div class="layout-padding-auto layout-padding-view">
          <el-table ref="multipleTable" :data="dataList" v-loading="state.loading" border
            :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
            @selection-change="selectionChangHandle">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column type="index" label="序号" width="80" />
            <!-- <el-table-column prop="placeId" label="所属区域" show-overflow-tooltip /> -->
            <el-table-column prop="id" label="id" show-overflow-tooltip />
            <el-table-column prop="name" label="点位名称" show-overflow-tooltip />
            <!-- <el-table-column prop="videoUrl" label="视频点位url" show-overflow-tooltip /> -->
          </el-table>

        </div>
      </pane>
    </splitpanes>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onUpdate" :disabled="loading">更新</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserVideoDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { BasicTableProps, useTable } from "/@/hooks/table";
const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/index.vue'));
import { getObj, addObj, putObj, deptTree, fetchVideoList } from '/@/api/backoffice/userVideo'
import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const multipleTable = ref()
const dataList = ref([])
// 定义字典
//  table hook
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: { placeId: "1" },
  pageList: fetchVideoList
})

// 部门树使用的数据
const deptData = reactive({
  queryList: (name: String) => {
    return deptTree({
      deptName: name,
    });
  },
});
// 点击树
const handleNodeClick = (e: any) => {
  state.queryForm.placeId = e.id;
  getDataList();
};

const getDataList = () => {
  fetchVideoList({ placeId: state.queryForm.placeId }).then((res: any) => {
    dataList.value = res.data
    const arr = form.regionAuthority.split(",");
    if (form.id != '') {
      nextTick(() => {
        if (dataList.value.length > 0) {
          dataList.value.forEach((row: any) => {
            const index1 = arr.findIndex(item => item === row.id + '')
            if (index1 != -1) {  //单个情况回显
              selectObjs.value.push(row)
              multipleTable.value.toggleRowSelection(row, true) // 默认勾选
            } else {
              multipleTable.value.toggleRowSelection(row, false) // 不选中
            }
          })
        } else {
          multipleTable.value!.clearSelection()
        }
      })
    } else {
      multipleTable.value!.clearSelection()
    }

  })
}
const {
  sortChangeHandle,
  tableStyle
} = useTable(state)
// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};
// 提交表单数据
const form = reactive({
  id: '',
  username: '',
  regionAuthority: '',
});

// 定义校验规则
const dataRules = ref({
})

// 打开弹窗
const openDialog = (id: string) => {
  console.log('id', id);

  visible.value = true
  form.id = ''
  // 重置表单数据
  nextTick(() => {
    state.queryForm.value?.resetFields();
  });
  state.queryForm.placeId = '';
  getDataList();
  // 获取userVideo信息
  if (id) {
    form.id = id
    getuserVideoData(id)
  }
};

//更新
const onUpdate = async () => {
  loading.value = true
  console.log('selectObjs', selectObjs);

  const authorities = []
  for (let index = 0; index < dataList.value.length; index++) {
    console.log('dataList.value[index]', dataList.value[index]);

    const index1 = selectObjs.value.findIndex(item => item === dataList.value[index].id)

    console.log('index', index1);

    if (index1 != -1) {
      authorities.push({
        id: dataList.value[index].id,
        flag: true
      })
    } else {
      authorities.push({
        id: dataList.value[index].id,
        flag: false
      })
    }
  }
  console.log('authorities', authorities);
  form.id ? await putObj({ id: form.id, username: form.username, authorities: authorities }) : await addObj({ id: form.id, username: form.username, authorities: authorities });

  visible.value = false;
  emit('refresh');
}

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getuserVideoData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>